package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.core.xml.StubObject;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.service.Registry;
import com.efounder.utils.JfResourceUtil;
import com.pansoft.newasset.bean.MenuBean;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.AssetAllAppAdapter;
import com.pansoft.openplanet.adapter.AssetEditAppDragAdapter;
import com.pansoft.openplanet.bean.AllAppTabItemBean;
import com.pansoft.openplanet.bean.EventMenuBean;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.utilcode.util.*;
import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author : zzj
 * @e-mail : zhangzhijun@pansoft.com
 * @date : 2019/4/25 9:21
 * @desc : 更多中的编辑应用界面
 * @version: 1.0
 */
public class AssetEditApplicationActivity extends BaseActivity {
    /**
     * 首页应用 全部应用 编辑应用 缓存sp name
     */
    public static final String ASSET_MENU = "asset_menu";
    /**
     *  标题
     */

    private TextView tv_title;
    /**
     * 保存
     */
    private TextView tv_save;
    private QMUITabSegment tabLayout;
    /**
     * 功能列表
     */
    private RecyclerView recycler_view;
    /**
     *  顶部的图标列表
     */
    private RecyclerView rv_top;

    private RelativeLayout rl_title;
    /**
     * 功能集合
     */
    private List<AllAppTabItemBean> tabItemBeans = new ArrayList<>();
    /**
     * 功能列表的adapter
     */
    private AssetAllAppAdapter assetAllAppAdapter;
    /**
     * 顶部图标列表的adapter
     */
    private AssetEditAppDragAdapter topAdapter;
    private ItemTouchHelper mItemTouchHelper;
    private ItemDragAndSwipeCallback mItemDragAndSwipeCallback;

    /**
     * tab 的菜单集合
     */
    private String[] tabMenus ;

    /**
     * recyclerView是否滚动
     */
    private boolean isScroll = false;

    /**
     * item的高度
     */
    private int itemHeight;

    /**
     * 是否已经添加过空白布局
     */
    private boolean isAddEmptyLayout;
    /** 顶部布局是否在拖拽*/
    private boolean isDragItem;
    private int firstPosition = -2;
    private List<MenuBean> menuBeans = new ArrayList<>();
    private List<StubObject> mainMenus;

    public static void start(Context context) {
        Intent starter = new Intent(context, AssetEditApplicationActivity.class);
        context.startActivity(starter);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity_edit_application);
        tabMenus = new String[]{getString(R.string.open_planet_asset_all_app_comm)/*,getString(R.string.open_planet_asset_all_app_other)*/};
        initView();
        initTopDragAdapter();
        initListener();
        //监听顶部recyclerview的布局变化，控制底部空白布局的高度
        rv_top.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                //根据布局变化，控制底部空白的高度
                if(isAddEmptyLayout && !isDragItem){
                    addBottomEmptyLayout(itemHeight);
                }
            }
        });
    }


    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.open_planet_asset_all_app_edit));
        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_save.setText(getResources().getString(R.string.common_text_complete));
        tv_save.setVisibility(View.VISIBLE);
        tabLayout = (QMUITabSegment) findViewById(R.id.tab);
        rv_top = (RecyclerView) findViewById(R.id.rv_top);
        rl_title = (RelativeLayout) findViewById(R.id.title);
        //获取菜单列表
        getMenuList();
        rv_top.setLayoutManager(new GridLayoutManager(this,4));

        recycler_view = (RecyclerView) findViewById(R.id.rv_menu_list);
        recycler_view.setLayoutManager(new GridLayoutManager(this,4));
//        tabItemBeans = getSampleData();
        assetAllAppAdapter = new AssetAllAppAdapter(R.layout.assets_item_edit_app_content_layout,R.layout.asset_item_all_app_header_layout,tabItemBeans,true);
        recycler_view.setAdapter(assetAllAppAdapter);
        iniTabLayout();

    }

    private void iniTabLayout() {
        tabLayout.reset();
        //添加菜单
        QMUITabBuilder tabBuilder = tabLayout.tabBuilder();
//        tabBuilder.setColorAttr(R.color.black_text_color, R.color.title_Background);
        for (String tab : tabMenus) {
            tabLayout.addTab(tabBuilder.setText(tab)
                    .build(this));
        }
        tabLayout.setMode(QMUITabSegment.MODE_SCROLLABLE);
//        tabLayout.setDefaultNormalColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
//        tabLayout.setDefaultSelectedColor(JfResourceUtil.getSkinColor(R.color.title_Background));

        tabLayout.setDefaultTextSize(ConvertUtils.dp2px(15), ConvertUtils.dp2px(15));
        tabLayout.notifyDataChanged();
    }
    /**
     * 读取菜单配置
     */
    private void getMenuList() {
        //1、获取缓存的菜单数据
        boolean isCache = !SPUtils.getInstance(AssetEditApplicationActivity.ASSET_MENU).getString("NewAssetRoot","").equals("");
        //2.如果有缓存从缓存中读取，否则从配置菜单中读取
        if(isCache){
            //2.1 读取缓存数据
            String cacheMenu = SPUtils.getInstance(AssetEditApplicationActivity.ASSET_MENU).getString("NewAssetRoot","");
            //2.2解析缓存菜单集合
            List<MenuBean> cacheMenuBeas = JSONArray.parseArray(cacheMenu,MenuBean.class);
            //2.3 加载数据到顶部列表中
            menuBeans.addAll(cacheMenuBeas);
        }
        //1、加载全部的功能列表菜单
        mainMenus = Registry.getRegEntryList("NewAssetRoot");
        if (mainMenus != null) {

            //2、循环配置数据 去除更多菜单
            for (int i = 0; i < (mainMenus.size()-1); i++) {
                StubObject stubObject = mainMenus.get(i);
                //3、判断该菜单是否在顶部
                boolean isShow = false;
                //4、循环顶部列表菜单，设置状态 根据显示加减号提示
                for(int j = 0;j<menuBeans.size();j++){
                    //4.1 如果当前菜单在顶部显示  设置true
                    if(stubObject.getCaption().equals(menuBeans.get(j).getName())){
                        isShow = true;
                    }
                }
                MenuBean menuBean = new MenuBean(stubObject.getString("icon", ""),
                        stubObject.getCaption(),
                        stubObject.getString("AndroidShow", ""),stubObject.getString("multiLanguageKey",""),isShow);
                menuBean.setStubObject(stubObject);
                //没有缓存添加配置文件中数据
                if(!isCache&&i<7){
                    menuBean.setShow(true);
                    menuBeans.add(menuBean);
                }
                tabItemBeans.add(new AllAppTabItemBean(menuBean));

            }

//            tabItemBeans.add(new AllAppTabItemBean(true, getResources().getString(R.string.open_planet_asset_all_app_other)));
//            tabItemBeans.add(new AllAppTabItemBean(new MenuBean(menuBeans.get(0).getIcon(),menuBeans.get(0).getName(),menuBeans.get(0).getClassName(),false)));
        }

    }

    /**
     * 初始化顶部拖拽适配器
     */
    private void initTopDragAdapter(){
        OnItemDragListener listener = new OnItemDragListener() {
            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {
                isDragItem = true;
//                Log.d(TAG, "drag start");
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);
//                holder.setTextColor(R.id.tv, Color.WHITE);
            }

            @Override
            public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {
//                Log.d(TAG, "move from: " + source.getAdapterPosition() + " to: " + target.getAdapterPosition());
            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
                isDragItem = false;
//                Log.d(TAG, "drag end");
                BaseViewHolder holder = ((BaseViewHolder) viewHolder);

//                holder.setTextColor(R.id.tv, Color.BLACK);
            }
        };
        topAdapter = new AssetEditAppDragAdapter(R.layout.assets_item_edit_app_content_layout,menuBeans);
        mItemDragAndSwipeCallback = new ItemDragAndSwipeCallback(topAdapter);
        mItemTouchHelper = new ItemTouchHelper(mItemDragAndSwipeCallback);
        mItemTouchHelper.attachToRecyclerView(rv_top);

        topAdapter.enableDragItem(mItemTouchHelper);
        topAdapter.setOnItemDragListener(listener);
        rv_top.setAdapter(topAdapter);
    }


    /**
     * 点击事件
     */
    private void initListener(){
        /**
         * 完成按钮的点击事件
         */
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save();
            }
        });
        //顶部列表加减号的点击事件
        topAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //移除相应的位置菜单
                if(view.getId() == R.id.iv_operation_app){
                    //1、获取当前顶部点击的菜单实体类
                    MenuBean menuBean = topAdapter.getData().get(position);
                    //2、循环功能列表数据将点击的菜单设置为未在顶部显示
                    for(AllAppTabItemBean allAppTabItemBean: tabItemBeans){
                        if(allAppTabItemBean.t!=null&&allAppTabItemBean.t.getName().equals(menuBean.getName())){
                            allAppTabItemBean.t.setShow(false);
                            assetAllAppAdapter.notifyDataSetChanged();
                            break;
                        }
                    }

                    //3、移除顶部点击的位置菜单
                    topAdapter.getData().remove(position);
                    //两个列表更新
                    topAdapter.notifyDataSetChanged();
                    //重新设置布局，防止notifyDataSetChanged无效
                    recycler_view.requestLayout();

                }
            }
        });
        //列表菜单的加减号点击事件
        assetAllAppAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //1、获取点击的菜单列表的实体类
                AllAppTabItemBean allAppTabItemBean = tabItemBeans.get(position);
                //2、判断当前菜单是否在顶部显示
                if(allAppTabItemBean.t.isShow()){
                    //2.1 在顶部显示就将其移除，并设置状态为false
                    for(MenuBean menuBean: topAdapter.getData()){
                        if(allAppTabItemBean.t.getName().equals(menuBean.getName())){
                            topAdapter.getData().remove(menuBean);
                            break;
                        }
                    }
                    allAppTabItemBean.t.setShow(false);
                }else {
                    //2.2 如果没有在顶部显示  判断顶部的应用是否大于7个  大于提示不能添加  小于执行添加
                    //2.2.1获取顶部菜单数量
                    int size = topAdapter.getData().size();
                    if(size<7){
                        //小于执行添加
                        topAdapter.getData().add(allAppTabItemBean.t);
                        allAppTabItemBean.t.setShow(true);
                    }else {
                        //大于提示不能添加
                        ToastUtils.showShort(getString(R.string.open_planet_asset_all_app_most_seven));
                    }
                }
                //更新
                topAdapter.notifyDataSetChanged();
                assetAllAppAdapter.notifyDataSetChanged();
                //重新设置布局，防止notifyDataSetChanged无效
                recycler_view.requestLayout();
            }
        });
        //recyclerView 菜单列表滑动监听
        recycler_view.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //平滑移动需要在此处判断处理没有到顶部的position
                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {//
//                    firstPosition = 0;
//                    mShouldScroll = false;
//                    smoothMoveToPosition(recycler_view, mToPosition);
                }else if(RecyclerView.SCROLL_STATE_IDLE == newState){
                    isScroll = false;

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(isScroll){
                    return;
                }
                firstPosition = 0;
                LinearLayoutManager layoutManager = (LinearLayoutManager) recycler_view.getLayoutManager();
                //获取第一个显示的位置
                int position = layoutManager.findFirstVisibleItemPosition();
                //获取第一个位置item的View
                View firstVisiableChildView = layoutManager.findViewByPosition(position);
                //获取第一个位置item的高度，用于计算空白区域的高度
                itemHeight = firstVisiableChildView.getHeight();
                //如果position大于等于列表集合的长度，return
                if(position>=tabItemBeans.size()){
                    return;
                }
                AllAppTabItemBean allAppTabItemBean = tabItemBeans.get(position);
                //如果第一个item位置position为0，tabLayout指定为0，并添加空白布局
                if(position == 0){
                    tabLayout.selectTab(0);
                    //判断是否已经添加，只添加一次
                    if(!isAddEmptyLayout){
                        //添加recyclerView底部空白布局
                        addBottomEmptyLayout(itemHeight);
                        isAddEmptyLayout = true;
                    }
                }
                if(allAppTabItemBean.header == null){
                    return;
                }
                /**
                 * 根据滚动的item 指定tab菜单的位置
                 */
                for(int i = 0;i<tabMenus.length;i++){
                    if(allAppTabItemBean.header.equals(tabMenus[i])){
                        tabLayout.selectTab(i);
                    }
                }
            }
        });
        /**
         * tab的点击事件 控制列表的位置
         */
        tabLayout.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public void onTabClick(int index) {
                tabClick(index);
            }
        });
    }
    /**
     * 保存按钮的事件执行方法
     */
    private void save(){
//        StubObject stubObject = mainMenus.get(mainMenus.size()-1);
        //获取当前排序的菜单列表集合
        List<MenuBean> menuBeans = topAdapter.getData();
        //添加更多菜单按钮
//        menuBeans.add(new MenuBean(stubObject.getString("icon", ""),
//                stubObject.getCaption(),
//                stubObject.getString("AndroidShow", ""),true));
        //保存本地缓存中
        String menuBeanJson = JSONArray.toJSONString(menuBeans);
        SPUtils.getInstance(ASSET_MENU).put("NewAssetRoot",menuBeanJson);
        //通知首页应用和全部应用页面更新
        EventBus.getDefault().post(new EventMenuBean(0));
        finish();
    }
    /**
     * tabLayout的点击事件执行的方法
     * @param index 点击的位置
     */
    private void tabClick(int index){
        if(index == 0){
            firstPosition = 0;
            recycler_view.scrollToPosition(0);
            return;
        }
        String title = tabLayout.getTab(index).getText().toString();
        for(int i = 0;i<tabItemBeans.size();i++){
            AllAppTabItemBean tabItemBean = tabItemBeans.get(i);
            if(tabItemBean.header!=null&&title.equals(tabItemBean.header)){

                moveToPosition(i);
            }
        }
    }
    /**
     * 控制recyclerView底部的空白区域
     * @param itemHeight
     */
    private void addBottomEmptyLayout(int itemHeight){
        //最后一栏的数量
        int i = 0;
        List<AllAppTabItemBean> appTabItemBeans = new ArrayList<>();
        appTabItemBeans.addAll(tabItemBeans);
        //集合倒叙，便于循环菜单的数量
        Collections.reverse(appTabItemBeans);
        //计算最后一栏的数量
        for(AllAppTabItemBean tabItemBean : appTabItemBeans){
            if(tabItemBean.header!=null){
                break;
            }
            i++;

        }
        //最后一栏的行数
        int count = 0;
        if((i%4)>0){
            count = ((int)(i/4))+1;
        }else if(i%4 == 0){
            count = i/4;
        }else if(i%4<0){
            count = 1;
        }
        //移除底部布局
        assetAllAppAdapter.removeAllFooterView();
        //空白布局
        View view = LayoutInflater.from(AssetEditApplicationActivity.this).inflate(R.layout.asset_item_header_total_layout,recycler_view,false);
        FrameLayout frameLayout = view.findViewById(R.id.fl_view);
        GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) frameLayout.getLayoutParams();
        //item的高度
        int itemHeightSum = ((count)*itemHeight);
        //item标题的高度
        final int marginHeight = ConvertUtils.dp2px(40);
        layoutParams.height = recycler_view.getMeasuredHeight()-itemHeightSum-marginHeight;
        frameLayout.setLayoutParams(layoutParams);
        //仿支付宝添加空白布局
        assetAllAppAdapter.addFooterView(view);

    }

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;


    /**
     *  非平滑移动   指定某个位置移动到顶部
     * @param position
     */
    private void moveToPosition(int position) {
        if (position != -1) {
            recycler_view.scrollToPosition(position);
            LinearLayoutManager mLayoutManager =
                    (LinearLayoutManager) recycler_view.getLayoutManager();
            mLayoutManager.scrollToPositionWithOffset(position, 0);
        }
    }

}
